from datetime import datetime
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import GenericAPIView, CreateAPIView, RetrieveAPIView
from rest_framework.mixins import RetrieveModelMixin, UpdateModelMixin, CreateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet, GenericViewSet
from rest_framework_jwt.settings import api_settings
from rest_framework_jwt.views import ObtainJSONWebToken, jwt_response_payload_handler

from cart.utils import merge_cookie_cart_to_redis
from goods.models import SKU
from goods.serializers import SKUSerializer
from users import constants
from users.models import User, Address
from users.serializers import UserSerializer, UserDetailSerializer, EmailSerializer, AddressSerializer, \
    AddressTitleSerializer, BrowseHistorySerializer


# POST /browse_histories/
class BrowseHistoryView(CreateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = BrowseHistorySerializer
    def get(self, request):
        '''
        用户中心界面获取浏览历史记录
        :param request:
        :return:
        '''
        user_id = request.user.id
        from django_redis import get_redis_connection
        redis_conn = get_redis_connection('histories')
        sku_id_list = redis_conn.lrange('history_%s'%user_id, 0, -1)
        skus = []
        for sku_id in sku_id_list:
            sku = SKU.objects.get(id=sku_id) # 不用进行byte类型转换 自动转换
            skus.append(sku)
        serializer = SKUSerializer(skus, many=True)
        return Response(serializer.data)

    # def post(self, request):
    #     '''
    #     登录用户浏览数据时候添加浏览记录
    #     :参数sku_id 必传
    #     :return: 可传good 可以传参数sku_id返回数据
    #     '''
    #     serializer = self.get_serializer(data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #     serializer.save()
    #     return Response(serializer.data, status=status.HTTP_201_CREATED)

class AddressViewSet(UpdateModelMixin, CreateModelMixin, GenericViewSet):
    serializer_class = AddressSerializer
    permission_classes = [IsAuthenticated]
    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)
    # 保存新增 /address/
    def create(self, request, *args, **kwargs):
        count = self.get_queryset().count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '地址数量超过上限'}, status=status.HTTP_400_BAD_REQUEST)
        # serializer = self.get_serializer(data=request.data)
        # serializer.is_valid(raise_exception=True)
        # serializer.save()
        return super().create(request)
    # 获取用户的所有地址/addresses/
    def list(self, request):
        addss = self.get_queryset()
        serializer = self.get_serializer(addss, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address.id if user.default_address else None,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })
    # 修改 /addresses/(?P<pk>\d+)
    # def update(self, request, pk):
    #     addss = self.get_object()
    #     serializer = self.get_serializer(addss, data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #     serializer.save()
    #     return Response(serializer.data)
    # 删除 /addresses/(?P<pk>\d+)
    def destroy(self, request, pk):
        addss = self.get_object()
        addss.is_deleted = 1
        addss.save()
        return Response(status=status.HTTP_204_NO_CONTENT)
    # 设置默认 /addresses/1/status/
    @action(methods=['put'], detail=True)
    def status(self, request, pk):
        addss = self.get_object()
        request.user.default_address = addss
        return Response({'message': 'ok'})
    # 修改标题 /addresses/1/title/
    @action(methods=['put'], detail=True)
    def title(self, request, pk):
        addss = self.get_object()
        serializer = AddressTitleSerializer(addss, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)
# get /emails/verification/?token=
class EmailVerificationView(APIView):
    # 修改邮箱验证状态
    def put(self, request):
        token = request.query_params.get('token')
        if token is None:
            return Response({'message': '缺少token参数'}, status=status.HTTP_400_BAD_REQUEST)
        # 对token进行解密
        user = User.check_email_verify_token(token)
        if user is None:
            return Response({'message': '无效的token'}, status=status.HTTP_400_BAD_REQUEST)
        user.email_active = True
        user.save()
        return Response({'message':'ok'})

# put /email/
class EmailView(GenericAPIView):
    # 修改邮箱,并在序列化器里发送邮件
    permission_classes = [IsAuthenticated]
    serializer_class = EmailSerializer
    def put(self, request):
        user = request.user
        serializer = self.get_serializer(user, request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)

# get /user/
# class UserDetailView(GenericAPIView, RetrieveModelMixin):
class UserDetailView(RetrieveAPIView):
    # 用户中心 获得用户信息
    permission_classes = [IsAuthenticated]
    serializer_class = UserDetailSerializer
    def get_object(self):
        return self.request.user
    # def get(self, request):
    #     user = request.user
    #     serializer = self.get_serializer(user)
    #     return Response(serializer.data)

'''
参数:
	{
        "username": "账户名",
        "password": "密码"
	}
响应:
	{
        "user_id": "用户id",
        "username": "用户名",
        "token": "jwt token"
	}
'''
'''
    POST /authorizations/ 登录试图不用我们写,JWT拓展中为我们提供了一个登录试图
from rest_framework_jwt.views import obtain_jwt_token 直接在url中配置就好
但是他之返回token,我们要他额外返回id 用户名,就需要重写该方法
因为在购物车合并中要给登录试图中添加数据，所以又得来定义重新该试图
'''
class AuthorizationsView(ObtainJSONWebToken):
    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            token = serializer.object.get('token')
            response_data = jwt_response_payload_handler(token, user, request)
            response = Response(response_data)
            if api_settings.JWT_AUTH_COOKIE:
                expiration = (datetime.utcnow() +
                              api_settings.JWT_EXPIRATION_DELTA)
                response.set_cookie(api_settings.JWT_AUTH_COOKIE,
                                    token,
                                    expires=expiration,
                                    httponly=True)
            # 进行购物车记录合并
            merge_cookie_cart_to_redis(request, user, response)
            return response

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
'''
参数:
	{
        "username": "用户名",
        "password": "密码",
        "password2": "重复密码",
        "mobile": "手机号",
        "sms_code": "短信验证码",
        "allow": "是否同意协议" # 'true': 同意
	}
响应:
	{
        "id": "用户id",
        "username": "用户名",
        "mobile": "手机号",
        "token": "jwt token"
	}
'''
# POST /users/
class UserView(CreateAPIView):
    '''
    注册
    '''
    serializer_class = UserSerializer

    # def post(self, request):
    #     '''
    #     1 校验参数(判断参数完整性,用户名不能全为数字,两次密码是否相同,手机号格式,短信验证码,是否同意协议,)
    #     '''
    #     serializer = self.get_serializer(data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #     serializer.save()
    #     return Response(serializer.data, status=status.HTTP_201_CREATED)

# 用户名是否已经存在
class UsernameCountView(APIView):
    #/usernames/(?P<username>\w{5,9})/count
    def get(self, request, username):
        user_count = User.objects.filter(username=username).count()
        res_data = {
            'username': username,
            'count': user_count
        }
        return Response(res_data)

# GET /mobiles/(?P<mobile>1[3-9]\d{9})/count/
class MobileCountView(APIView):
    def get(self, request, mobile):
        """
        获取用户名数量:
        1. 根据手机号查询数据库，获取查询结果数量
        2. 返回用手机号数量
        """
        # 1. 根据用户名查询数据库，获取查询结果数量
        count = User.objects.filter(mobile=mobile).count()

        # 2. 返回用户名数量
        res_data = {
            'mobile': mobile,
            'count': count
        }
        return Response(res_data)